package com.yanghs.shiro.session;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;

import java.io.Serializable;
import java.util.Collection;

/**
 * @author yanghs
 * @Description:实现自定义的session管理
 * @date 2018/3/22 10:32
 */
public class RedisSessionDao extends AbstractSessionDAO{
    private IRedisRepository redisSessionRepository;

    public RedisSessionDao(IRedisRepository redisSessionRepository) {
        this.redisSessionRepository = redisSessionRepository;
    }

    protected Serializable doCreate(Session session) {
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        redisSessionRepository.saveSession(session);
        return sessionId;
    }

    protected Session doReadSession(Serializable serializable) {

        return redisSessionRepository.getSession(serializable);
    }

    public void update(Session session) throws UnknownSessionException {

        /*会话过期不更新了*/
        if(session instanceof ValidatingSession  && !((ValidatingSession)session).isValid()){
            return;
        }
        redisSessionRepository.saveSession(session);
    }

    public void delete(Session session) {
        redisSessionRepository.deleteSession(session.getId());
    }

    public Collection<Session> getActiveSessions() {

        return redisSessionRepository.getAllSession();
    }
}
